//
//  AppDelegate.m
//  KWNLaywerClient
//
//  Created by 张明磊 on 14/11/6.
//  Copyright (c) 2014年 张明磊. All rights reserved.
//

#import "AppDelegate.h"
#import "KWLHomeViewController.h"
#import "KWLLeftSideViewController.h"
#import "UncaughtExceptionHandler.h"
#import "MLBlackTransition.h"
#import "UMessage.h"
#import "RESideMenu.h"
#import "Model_user.h"
#import "KWLLoginViewController.h"
#import "KWNNetwork.h"
#import "YXBeginViewController.h"
#import "UMFeedback.h"
#import "MINavigationController.h"
#import "KWLAppConsole.h"
#import "SDImageCache.h"
//#import "UMSocial.h"
//#import "UMSocialSinaHandler.h"

@interface AppDelegate ()<RESideMenuDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    InstallUncaughtExceptionHandler();
    if(IOS7_VERSION){
        [MLBlackTransition validatePanPackWithMLBlackTransitionGestureRecognizerType:MLBlackTransitionGestureRecognizerTypePan];
        [application setStatusBarHidden:NO];
        [application setStatusBarStyle:UIStatusBarStyleLightContent];
    }
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    [[SDImageCache sharedImageCache]setMaxMemoryCost:100];
    
    [UIUtils cutInputTextTime];
    
    //友盟配置
    [self UM_pushConfigureWithOptions:launchOptions];
    [MobClick startWithAppkey:UM_AppKey];
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    [UMFeedback setAppkey:UM_AppKey];
    
    [MobClick checkUpdate:@"更新" cancelButtonTitle:@"不升级" otherButtonTitles:@"一键升级"];
    //[UMSocialData setAppKey:UM_AppKey];
    //[UMSocialSinaHandler openSSOWithRedirectURL:nil];
    
    KWLHomeViewController *controller_root = [[KWLHomeViewController alloc] init];
    KWLLeftSideViewController *controller_left = [[KWLLeftSideViewController alloc] init];
    RESideMenu *sideMenuViewController = [[RESideMenu alloc] initWithContentViewController:controller_root menuViewController:controller_left];
    sideMenuViewController.backgroundImage = [UIImage imageFileName:@"imageView_menuBack.png"];
    sideMenuViewController.contentViewScaleValue = 0.9;
    sideMenuViewController.contentViewInPortraitOffsetCenterX = 95;
    [sideMenuViewController setScaleBackgroundImageView:NO];
    sideMenuViewController.parallaxEnabled = NO;
    //sideMenuViewController.panGestureEnabled = NO;
    sideMenuViewController.menuPreferredStatusBarStyle = UIStatusBarStyleLightContent;
// AS 快法务 KLW 2014-12-26
    sideMenuViewController.delegate = self;
// AE 快法务 KLW 2014-12-26
    if(IOS6_VERSION){
        MINavigationController *navigation_root = [[MINavigationController alloc] initWithRootViewController:sideMenuViewController];
        controller_root.navigationController_MI = navigation_root;
        controller_left.navigationController_MI = navigation_root;
        if ([UIUtils isFirstLogin]) {
            [Model_user sharedInstance].bool_isFirst = YES;
            [Model_user sharedInstance].bool_isFirst_two = YES;
            YXBeginViewController *controller_begin = [[YXBeginViewController alloc] init];
            [navigation_root pushViewController:controller_begin animated:NO];
            [navigation_root enabledMLBlackTransition:NO];
        }
        else{
            [Model_user sharedInstance].bool_isFirst = NO;
            [Model_user sharedInstance].bool_isFirst_two = NO;
            NSString *string_token = [[Model_user sharedInstance] getToken];
            if(!string_token){
                KWLLoginViewController *controller_login = [[KWLLoginViewController alloc] initWithTag:5];
                [navigation_root pushViewController:controller_login animated:NO];
                [navigation_root enabledMLBlackTransition:NO];
            }
            [[KWNNetwork sharedInstance] score_openAppFirstOneDay];
        }
        self.window.rootViewController = navigation_root;
    }
    else{
        UINavigationController *navigation_root = [[UINavigationController alloc] initWithRootViewController:sideMenuViewController];
        navigation_root.navigationBarHidden = YES;
        if ([UIUtils isFirstLogin]) {
            [Model_user sharedInstance].bool_isFirst = YES;
            [Model_user sharedInstance].bool_isFirst_two = YES;
            YXBeginViewController *controller_begin = [[YXBeginViewController alloc] init];
            [navigation_root pushViewController:controller_begin animated:NO];
            [navigation_root enabledMLBlackTransition:NO];
        }
        else{
            [Model_user sharedInstance].bool_isFirst = NO;
            [Model_user sharedInstance].bool_isFirst_two = NO;
            NSString *string_token = [[Model_user sharedInstance] getToken];
            if(!string_token){
                KWLLoginViewController *controller_login = [[KWLLoginViewController alloc] initWithTag:5];
                [navigation_root pushViewController:controller_login animated:NO];
                [navigation_root enabledMLBlackTransition:NO];
            }
            [[KWNNetwork sharedInstance] score_openAppFirstOneDay];
        }
        self.window.rootViewController = navigation_root;
    }
    application.applicationIconBadgeNumber = 0;
    [self.window makeKeyAndVisible];
    
// AS 快法务 KLW 2014-12-29
    NSString *string_uid = [[Model_user sharedInstance] getUserID];
    if (string_uid) {
        [controller_root isLoginstu:0];
    }
// AE 快法务 KLW 2014-12-29
    
    return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    [UMessage addAlias:[UMFeedback uuid] type:@"umeng_feedback" response:^(id responseObject, NSError *error) {
        /*if (error != nil) {
            NSLog(@"%@", error);
            NSLog(@"%@", responseObject);
        }*/
    }];
    //NSString *tokeStr = [NSString stringWithFormat:@"%@",[deviceToken description]];
    NSString *dvsToken =[[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    dvsToken = [dvsToken stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([dvsToken length] == 0)
    {
        NSLog(@"获取token为空");
        return;
    }
    else
    {
        NSString *string_token = [[Model_user sharedInstance] getDeviceToken];
        if(!string_token || [string_token length] == 0)
        {
            [[Model_user sharedInstance] setDeviceToken:dvsToken];
            [UMessage registerDeviceToken:deviceToken];
            NSLog(@"未绑定设备,绑定。。。");
        }
        else
        {
            if([string_token isEqualToString:dvsToken])
            {
                NSLog(@"未变化");
            }
            else
            {
                NSLog(@"token发生变化,重新绑定。。。");
                [[Model_user sharedInstance] setDeviceToken:dvsToken];
                [UMessage registerDeviceToken:deviceToken];
            }
        }
    }
}

- (void)application:(UIApplication*)application
didFailToRegisterForRemoteNotificationsWithError:(NSError*)error{
    //NSLog(@"获得令牌失败: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    /**
     *  点击查看用户推送消息
     */
    [UMessage setAutoAlert:NO];
    [UMessage didReceiveRemoteNotification:userInfo];
    
    NSString *string_content = [[userInfo objectForKey:@"aps" ]objectForKey:@"alert"];
    UIAlertView *alter;
    if(IOS8_VERSION){
        alter = [[UIAlertView alloc] initWithTitle:string_content message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    }
    else{
        alter = [[UIAlertView alloc] initWithTitle:nil message:string_content delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    }
    [alter show];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    //从后台返回
    NSString *string_token = [[Model_user sharedInstance] getToken];
    if(string_token){
        [[KWNNetwork sharedInstance] score_openAppFirstOneDay];
    }
    NSString *string_count = [[Model_user sharedInstance] getUnReadCount];
    application.applicationIconBadgeNumber = string_count.integerValue;
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    /**
     *  后台进入前台
     */
    ZMViewController *viewController = [KWLAppConsole sharedInstance].viewController;
    [viewController handleEventWhenAppGoForeground];
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
//    //return  [UMSocialSnsService handleOpenURL:url];
//}
//
//- (BOOL)application:(UIApplication *)application
//            openURL:(NSURL *)url
//  sourceApplication:(NSString *)sourceApplication
//         annotation:(id)annotation{
//    //return  [UMSocialSnsService handleOpenURL:url];
//}

#pragma mark - 友盟推送注册 -
/**
 *  友盟推送注册
 */
- (void)UM_pushConfigureWithOptions:(NSDictionary *)launchOptions{
    NSDictionary * infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *identifier = [infoDictionary objectForKey:@"CFBundleIdentifier"];
    if([identifier isEqualToString:@"com.inHouseLawyer.distribution"]){
        //企业推送
        [UMessage startWithAppkey:UM_AppKey_InHousePush launchOptions:launchOptions];
    }
    else{
        //个人推送
        [UMessage startWithAppkey:UM_AppKey launchOptions:launchOptions];
    }
    //register remoteNotification types
    //register remoteNotification types (iOS 8.0以下)
    if(IOS8_VERSION){
        //[UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert];
        //register remoteNotification types （iOS 8.0及其以上版本）
        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"action1_identifier";
        action1.title=@"Accept";
        action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
        
        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
        action2.identifier = @"action2_identifier";
        action2.title=@"Reject";
        action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
        action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
        action2.destructive = YES;
        
        UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
        categorys.identifier = @"category1";//这组动作的唯一标示
        [categorys setActions:@[action1,action2] forContext:(UIUserNotificationActionContextMinimal)];
        UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:[NSSet setWithObject:categorys]];
        
        [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];
    }
    else{
        [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert];
    }
    [UMessage addTag:@"律师" response:^(id responseObject, NSInteger remain, NSError *error) {
        //add your codes
    }];
    [UMessage setLogEnabled:NO];
    //关闭状态时点击反馈消息进入反馈页
    NSDictionary *notificationDict = [launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    [UMFeedback didReceiveRemoteNotification:notificationDict];
    //[UMessage unregisterForRemoteNotifications]; 关闭推送
}

#pragma mark - 菜单委托 -
- (void)sideMenu:(RESideMenu *)sideMenu willShowMenuViewController:(UIViewController *)menuViewController
{
    KWLLeftSideViewController *viewControl = (KWLLeftSideViewController *)menuViewController;
    [viewControl reloadLayerDataForTable];
}
@end
